from fastapi import status
from fastapi.exceptions import HTTPException
from passlib.context import CryptContext
from passlib.hash import pbkdf2_sha256
import jwt
from dotenv import dotenv_values

from models import User

config_credentials = dotenv_values(".env")


def get_hashed_password(password):
    return pbkdf2_sha256.hash(password)


async def very_token(token: str):
    try:
        payload = jwt.decode(token, config_credentials['TOKEN_SECRET'], algorithms=['HS256'])
        user = await User.get(id=payload.get('id'))
    except:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='Invalid token',
            headers={"WWW-Authenticate": "Bearer"}
        )
    return user


async def token_generator(username: str, password: str):
    user = await User.get(username=username)
    if user:
        if pbkdf2_sha256.verify(password, user.password):
            token_data = {
                "id": user.id,
                'username': user.username,
            }
            return jwt.encode(token_data, key=config_credentials['TOKEN_SECRET'], algorithm='HS256').decode('utf8')
        else:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail='Invalid password',
                headers={"WWW-Authenticate": "Bearer"}
            )
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail='No such user, register first!',
        headers={"WWW-Authenticate": "Bearer"}
    )
    # user = await authenticate_user(username, password)
